package com.moyu.admin.web;

import com.moyu.admin.bean.TreeNodePerm;
import com.moyu.admin.service.ISysPermissionService;
import com.moyu.data.domain.SysPermission;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin/permission")
@Slf4j
public class PermissionController {

  @Autowired private ISysPermissionService permissionService;

  @RequestMapping("/index")
  public String index() {
    return "/admin/permission/index";
  }

  @RequestMapping("/list")
  @ResponseBody
  public List<SysPermission> list() {
    return permissionService.list();
  }

  /**
   * 回显权限 //TODO 二级权限列表 多级需优化
   *
   * @param roleId
   * @return
   */
  @RequestMapping("/listNodes")
  @ResponseBody
  public List<TreeNodePerm> listNodes(Long roleId) {
    List<TreeNodePerm> list = permissionService.listNodes();
    List<Long> permId = permissionService.listByRoleId(roleId);
    for (TreeNodePerm node : list) {
      if (permId.contains(node.getPkId())) {
        node.setChecked();
      }
      if (CollectionUtils.isNotEmpty(node.getNodes())) {
        for (TreeNodePerm sub : node.getNodes()) {
          if (permId.contains(sub.getPkId())) {
            sub.setChecked();
          }
        }
      }
    }
    list.forEach(obj -> log.info(":> " + obj));
    return list;
  }
}
